package infra.jenkins.job;

import domain.model.project.BuildProjectType;
import domain.model.project.Project;
import domain.model.project.ProjectDeveloper;
import domain.model.project.ProjectType;
import infra.jenkins.env.ProjectEnvRetriever;
import infra.jenkins.job.template.TemplateRetriever;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import util.velocity.VelocityTemplateEngine;
import util.velocity.impl.VelocityTemplateEngineImpl;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Gregory Boissinot
 */
public class JobRetriever {

    public static final String SCM_SVN = "scm:svn:";
    public static final String SCM_CVS = "scm:cvs:";
    public static final String SCM_GIT = "git";
    private static final String SYNCHROTRON_SOLEIL_FR = "@synchrotron-soleil.fr";
    private final TemplateRetriever templateRetriever;
    private Logger logger = LoggerFactory.getLogger(JobRetriever.class);

    public JobRetriever(TemplateRetriever templateRetriever) {
        this.templateRetriever = templateRetriever;
    }

    private static String getEmails(BuildProjectType buildProjectType) {
        List<ProjectDeveloper> developers = buildProjectType.getProjectDeveloperList();
        StringBuilder sb = new StringBuilder();
        for (ProjectDeveloper developerDocument : developers) {
            if (developerDocument.getEmail() == null || developerDocument.getEmail().isEmpty()) {
                sb.append(developerDocument.getId()).append(SYNCHROTRON_SOLEIL_FR);
            } else {
                sb.append(developerDocument.getEmail());
            }
            sb.append(" ");
        }
        return sb.toString();
    }

    public String getJobConfigXML(Project project) {
        File templateFile = templateRetriever.getTemplateFile(project);
        ProjectEnvRetriever projectEnvRetriever = new ProjectEnvRetriever();
        Map<String, String> context = projectEnvRetriever.getMapEnv(project);

        Map<String, Object> vars = new HashMap<String, Object>();
        vars.putAll(context);
        vars.put("emails", getEmails(project));
        String scmURL = project.getProjectSCM().getScmConnection();
        logger.debug("scmURL={}", scmURL);
        if (scmURL.startsWith(SCM_CVS)) {
            System.out.println("CVS");
            String cvsURL = scmURL.replace(SCM_CVS, "");
            logger.debug("cvsURL={} ", cvsURL);
            String cvsRoot = cvsURL.substring(0, cvsURL.lastIndexOf(":"));
            logger.debug("cvsRoot={} ", cvsRoot);
            String moduleName = cvsURL.substring(cvsURL.lastIndexOf(":") + 1, cvsURL.length());
            logger.debug("moduleName={}", moduleName);
            vars.put("useCVS", true);
            vars.put("cvsRoot", cvsRoot);
            vars.put("cvsModule", moduleName);
        } else if (scmURL.startsWith(SCM_SVN)) {
            vars.put("useCVS", false);
            String svnURL = scmURL.replace(SCM_SVN, "");
            vars.put("svnModule", svnURL);
            logger.debug("svnModule={} ", svnURL);
        }
        //  TODO else if (scmURL.startsWith(SCM_GIT))

        VelocityTemplateEngine velocityTemplateEngine = new VelocityTemplateEngineImpl();
        return velocityTemplateEngine.applyTemplate(templateFile, vars);
    }

    private String getEmails(Project project) {
        ProjectType projectType = project.getProjectType();
        if (projectType instanceof BuildProjectType) {
            return getEmails((BuildProjectType) projectType);
        }
        return "";
    }

}
